import React, {useState} from 'react'
import {
    Row,
    Col,
    Flex,
    Typography,
    Button,
    Form,
    Input,
    Radio,
    Select,
    message
} from 'antd'
import Amap from '../components/Amap'
import {useEffect} from 'react'
import ManyUpload from '../components/ManyUpload'
import ImageIdUpload from '../components/ImageIdUpload'
import {sellerVerifyList} from '../service/seller'
import {useNavigate, useParams} from 'react-router-dom'
import {
    cityListAPI,
    provinceListAPI,
    shopAdd,
    shopDetail,
    shopEdit
} from '../service/shop'

export default function ShopAdd() {
    const navigate = useNavigate()
    // 商家id
    const [sellerId, setSellerId] = useState()
    // 获取传递的id
    const {id} = useParams()
    const isEditing = id !== undefined // 根据id是否存在判断是编辑还是添加
    // 商家列表
    const [sellerList, setSellerList] = useState([])
    // 保存所有省份
    const [provinceList, setProvinceList] = useState([])
    // 保存省份ID
    const [provinceId, setProvinceId] = useState()
    // 保存所有城市
    const [cityList, setCityList] = useState([])
    // 保存城市ID
    const [cityId, setCityId] = useState()
    // 保存所有区域
    const [districtList, setDistrictList] = useState([])
    // 保存区域ID
    const [districtId, setDistrictId] = useState()
    // 保存Logo
    const [imageLogo, setImageLogo] = useState()
    const [imageId, setImageId] = useState()
    // 图片列表
    const [fileList, setFileList] = useState([])
    const [form] = Form.useForm()
    const [position, setPosition] = useState({
        longitude: 116.397428,
        latitude: 39.90923
    })
    useEffect(() => {
        ;(async () => {
            // 获取商家列表
            const res = await sellerVerifyList({pageSize: 200})
            console.log(res)
            if (res.data) {
                setSellerList(res.data.objects)
            }
            // 获取所有省份
            const res2 = await provinceListAPI()
            console.log(res2)
            setProvinceList(res2.data)
        })()

        // 判断是编辑还是新增
        if (isEditing) {
            ;(async () => {
                const res = await shopDetail(id)
                console.log(res.data)
                // 设置地图的坐标
                setPosition({
                    longitude: res.data.storeLongitude,
                    latitude: res.data.storeLatitude
                })
                // 通过省份查询城市列表
                const res2 = await cityListAPI(res.data.provinceId)
                // 保存城市
                setCityList(res2.data)
                // 通过城市获取地区列表
                const res3 = await cityListAPI(res.data.cityId)
                setDistrictList(res3.data)
                form.setFieldsValue({
                    ...res.data,
                    zuobiao: `${res.data.storeLatitude}, ${res.data.storeLongitude}`
                })
                // setSellerId(res.data.sellerId)
                // 设置logo
                setImageLogo(res.data.storeLogo)
                // 设置图片列表
                setFileList(
                    res.data.pictureVOS.map((item) => {
                        return {
                            id: item.id,
                            url: item.image
                        }
                    })
                )
            })()
        }
    }, [])
    useEffect(() => {
        form.setFieldsValue({
            zuobiao: `${position.latitude}, ${position.longitude}`
        })
    }, [position.longitude])

    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={3}>信息管理</Typography.Title>
                    </Flex>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Typography.Title level={4}>
                        {isEditing ? '编辑商家' : '新增商家'}
                    </Typography.Title>
                </Col>
                <Col span={24}>
                    <Form
                        form={form}
                        labelCol={{
                            span: 2
                        }}
                        wrapperCol={{
                            span: 16
                        }}
                        onFinish={async (value) => {
                            const ids = fileList.map((item) => {
                                if (item.response) {
                                    return item.response.data.id
                                } else {
                                    return item.id
                                }
                            })
                            console.log(ids)
                            console.log(value)
                            delete value.zuobiao
                            value.storeLogo = imageId
                            value.longitude = position.longitude
                            value.latitude = position.latitude
                            value.storeImagesIds = ids
                            console.log(value)
                            // 如果是新增
                            if (!isEditing) {
                                const res = await shopAdd(value)
                                console.log(res)
                                if (res.code === '0') {
                                    message.success('新增成功')
                                    navigate('/admin/shop/list')
                                } else {
                                    message.error('新增失败')
                                }
                            } else {
                                // 如果是编辑
                                const res = await shopEdit({...value, id})
                                if (res.code === '0') {
                                    message.success('编辑成功')
                                    navigate('/admin/shop/list')
                                } else {
                                    message.error('编辑失败')
                                }
                            }
                        }}
                    >
                        <Form.Item
                            label="商家名称"
                            name="businessId"
                            rules={[{required: true, message: '请选择商家'}]}
                        >
                            <Select
                                placeholder="请选择商家"
                                options={sellerList}
                                fieldNames={{value: 'id', label: 'businessName'}}
                                style={{width: 400}}
                                onChange={(value) => {
                                    console.log(value)
                                    // setSellerId(value)
                                }}
                            />
                        </Form.Item>
                        <Form.Item
                            label="门店名称"
                            name="storeName"
                            rules={[{required: true, message: '请输入门店名称'}]}
                        >
                            <Input placeholder="请输入门店名称" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item
                            label="门店电话"
                            name="storePhone"
                            rules={[{required: true, message: '请输入门店电话'}]}
                        >
                            <Input placeholder="请输入门店电话" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item
                            label="负责人"
                            name="storeHeadName"
                            rules={[
                                {
                                    required: true,
                                    message: '负责人不能为空'
                                }
                            ]}
                        >
                            <Input placeholder="请输入负责人" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item
                            label="负责人电话"
                            name="storeHeadPhone"
                            rules={[{required: true, message: '请输入负责人电话'}]}
                        >
                            <Input placeholder="请输入负责人电话" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label="门店地区">
                            <Row>
                                <Col span={5}>
                                    <Form.Item name={'provinceId'}>
                                        <Select
                                            placeholder="省"
                                            style={{width: 150}}
                                            onChange={async (value) => {
                                                console.log(value)
                                                const res = await cityListAPI(value)
                                                console.log(res)
                                                setCityList(res.data)
                                                // 保存省份id
                                                setProvinceId(value)
                                                setDistrictList([])
                                                // 当选择省份后，区域部分还显示之前选中的内容，现在不能有内容显示
                                                form.setFieldsValue({
                                                    areaId: '',
                                                    cityId: ''
                                                })
                                            }}
                                            options={provinceList}
                                            fieldNames={{value: 'id', label: 'name'}}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={5}>
                                    <Form.Item name={'cityId'}>
                                        <Select
                                            placeholder="市"
                                            style={{width: 150}}
                                            options={cityList}
                                            fieldNames={{value: 'id', label: 'name'}}
                                            onChange={async (value) => {
                                                console.log(value)
                                                const res = await cityListAPI(value)
                                                console.log(res)
                                                setDistrictList(res.data)
                                                // 保存市id
                                                setCityId(value)
                                            }}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={5}>
                                    <Form.Item name={'areaId'}>
                                        <Select
                                            placeholder="区"
                                            style={{width: 150}}
                                            options={districtList}
                                            fieldNames={{value: 'id', label: 'name'}}
                                            onChange={(value) => {
                                                console.log(value)
                                                // 保存区id
                                                setDistrictId(value)
                                            }}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                            label="详细店址"
                            name="storeLocation"
                            rules={[{required: true, message: '请输入详细店址'}]}
                        >
                            <Input placeholder="请输入详细地址" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label="门店坐标" name="zuobiao">
                            <Input readOnly style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label=" " colon={false}>
                            <Amap
                                width="800"
                                height="200"
                                position={position}
                                setPosition={setPosition}
                            />
                        </Form.Item>
                        <Form.Item label="门店图片">
                            <ManyUpload fileList={fileList} setFileList={setFileList}/>
                        </Form.Item>
                        <Form.Item label="门店Logo">
                            <ImageIdUpload
                                imageUrl={imageLogo}
                                setImageUrl={setImageLogo}
                                imageId={imageId}
                                setImageId={setImageId}
                            />
                        </Form.Item>
                        <Form.Item label="商家简介" name="storeIntroduction">
                            <Input.TextArea
                                placeholder="请输入商家简介"
                                style={{width: 400}}
                            />
                        </Form.Item>
                        <Form.Item label="排序" name="sort" initialValue={1}>
                            <Select
                                placeholder="请选择门店状态"
                                style={{width: 400}}
                                options={[
                                    {
                                        value: 1,
                                        label: '升序'
                                    },
                                    {
                                        value: 2,
                                        label: '降序'
                                    }
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="营业时间" name="tradeTime">
                            <Input placeholder="请输入营业时间" style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label="门店状态" name="storeStatus" initialValue={0}>
                            <Radio.Group name="radioGroup">
                                <Radio value={0}>开启</Radio>
                                <Radio value={1}>禁用</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label=" " colon={false}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                style={{marginRight: 10}}
                            >
                                确定
                            </Button>
                            <Button type="default" htmlType="reset">
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
        </>
    )
}
